# 385 中等：迷你语法分析器


# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger:
#    def __init__(self, value=None):
#        """
#        If value is not specified, initializes an empty list.
#        Otherwise initializes a single integer equal to value.
#        """
#
#    def isInteger(self):
#        """
#        @return True if this NestedInteger holds a single integer, rather than a nested list.
#        :rtype bool
#        """
#
#    def add(self, elem):
#        """
#        Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
#        :rtype void
#        """
#
#    def setInteger(self, value):
#        """
#        Set this NestedInteger to hold a single integer equal to value.
#        :rtype void
#        """
#
#    def getInteger(self):
#        """
#        @return the single integer that this NestedInteger holds, if it holds a single integer
#        Return None if this NestedInteger holds a nested list
#        :rtype int
#        """
#
#    def getList(self):
#        """
#        @return the nested list that this NestedInteger holds, if it holds a nested list
#        Return None if this NestedInteger holds a single integer
#        :rtype List[NestedInteger]
#        """
from collections import deque


class Solution:
    def getNext(self, s, i):
        if s[i] == ']' and s[i - 1] == '[':
            return 'n', i + 1
        if not s[i].isdigit() and s[i] != '-':
            return s[i], i + 1
        else:
            if s[i] != '-':
                j = i
                while s[j].isdigit():
                    j += 1
                return s[i:j], j
            else:
                j = i + 1
                while s[j].isdigit():
                    j += 1
            return s[i:j], j

    def deserialize(self, s: str):
        # 只有唯一整数情况，返回整数
        if s[0] != '[':
            return NestedInteger(int(s))

        # 返回list
        num = deque()
        opr = deque()
        index = 0
        while index < len(s):
            c, index = self.getNext(s, index)
            if c[0].isdigit() or c[0] == '-':
                num.append(int(c))
            elif c != ']' and c != 'n':
                opr.append(c)
            else:
                temp = []
                while opr:
                    if c == ']':
                        temp.append(num.pop())
                    if opr.pop() == '[':
                        break
                temp.reverse()
                num.append(temp)

        return NestedInteger(list(num)[0])


s = Solution()
print(s.deserialize('[123,3,[12,54]]'))
